<?php

namespace app\controller\admin\basic;

use app\model\admin\basic\BasicContent;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Content extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info','import'];
    protected $type = 1;
    protected $orderRule =['sort'=>'desc','id'=>'asc'];
    public function initialize()
    {
        $this->model = new BasicContent();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            $data = $this->model->where($where)->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
                if (isset($item['url']) && !empty($item['url'])) {
                    $item['url'] = imgUrlToAbsolute($item['url']);
                }
                if (isset($item['icon']) && !empty($item['icon'])) {
                    $item['icon'] = imgUrlToAbsolute($item['icon']);
                }
            }
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        if(!$this->request->param("game_id")){
            return $this->error("缺少游戏id");
        }
        $gameId = $this->request->param("game_id");
        $post = CommonFun::filterPostData($this->request->post());
        try{
            $post['basic_game_id'] = $gameId;
            $post['type'] = $this->type;
            if ($this->model->create($post)) {
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    /**
     * 导入条数
     * @return false|string|\think\response\Json
     */
    public function import(){
        $file = $this->request->file("file");
        $game_id  = $this->request->post("game_id");
        $contentNames = (new BasicContent())->where("basic_game_id",$game_id)->column("name");
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
        $sheetData = $spreadsheet->getActiveSheet(1)->toArray(null, true, true, true);
        unset($sheetData[1]);
        $data = [];
        Db::startTrans();
        foreach ($sheetData as $item){
            if(empty($item['A'])||empty($item['B'])){
                continue;
            }
            if(!empty($item['B'])){
                $fileInfo = pathinfo($item['B']);
                $item['B'] = $fileInfo['dirname'].DIRECTORY_SEPARATOR.urlencode($fileInfo['basename']);
            }
            if(!filter_var($item['B'], FILTER_VALIDATE_URL)){
                continue;
            }
            if(in_array($item['A'],$contentNames)){
                continue;
            }else{
                array_push($contentNames,$item['A']);
            }
            $data[] = [
              'basic_game_id'=>$game_id,
              'name'=>$item['A'],
              'icon'=>$item['B'],
              'description'=>$item['C'],
              'append_description'=>$item['D'],
              'create_time'=>date("Y-m-d H:i:s"),
              'update_time'=>date("Y-m-d H:i:s"),
            ];
        }

        if(count($data)>0){
            (new BasicContent())->insertAll($data);
            Db::commit();
            return $this->success("上传成功".count($data)."条数据");
        }else{
            (new BasicContent())->insertAll($data);
            Db::rollback();
            return $this->success("0条有效数据上传成功");
        }
    }
}